<script setup>
	import {
		ref
	} from 'vue';
	import {
		onReachBottom
	} from "@dcloudio/uni-app"
	import dayjs from "dayjs"

	const db = uniCloud.database();
	const userList = ref([])
	const noData = ref(false)


	const queryParams = ref({
		pageNum: 1,
		pageSize: 7,
		total: 0
	})


	const getData = async () => {
		let current = queryParams.value.pageSize * (queryParams.value.pageNum - 1)
		let res = await db.collection('demo-user')
		//jql
		// .where(`name='小明' && age<30`)
		// .where(`name=['小明','小红']`)
		// 传统
		// .where({
		// 	name: "小明",
		// 	age: 20
		// })
		where(`${new RegExp(keyword.value, 'i')}.test(name)`)
			.orderBy("createTime desc")
			.skip(current) // 跳过前current条
			.limit(queryParams.value.pageSize) // 获取pageSize条
			.field("name as username,age,gender,createTime,avatar") //过滤，节省开支
			.get({
				getCount: true,
			})
		console.log(res);
		if (res.result.errCode === 0) {
			userList.value = [...userList.value, ...res.result.data];
			queryParams.value.total = res.result.count;
			// 判断数据是否小于固定值
			if (queryParams.value.pageSize > res.result.data.length) noData.value = true;
		} else {
			uni.showToast({
				title: res.result.errMag || "返回错误",
				icon: 'none'
			})
		}
	}
	// 触底加载
	onReachBottom(() => {
		// 判断noData
		if (noData.value) return;
		queryParams.value.pageNum++;
		getData();
	})
	// input框回车触发
	const onConfirm = () => {
		userList.value = [];
		getData();
	}
	// 跳转到详情页面
	const goDetail = (e) => {
		console.log(e);
		uni.navigateTo({
			url: "/pages/demo1/detail?id=" + e
		})
	}

	getData()
</script>
<template>
	<view class="layout">
		<view class="head">
			共{{queryParams.total}}条记录,已获取{{userList.length}}条
		</view>
		<input @confirm="onConfirm" type="text" class="search" v-model="keyword" placeholder="请输入搜索的内容">
		<view class="box" v-for="item,index	 in userList" :key="item._id" @click="goDetail(item._id)">
			<view>{{index+1}}</view>
			<view>{{item._id}}</view>
			<image v-if="item.avatar" :src="item.avatar[0].url" mode="widthFix"></image>
			<view>{{item.name}}</view>
			<view>{{item.age}}</view>
			<view>{{item.gender}}</view>
			<view>{{dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss")}}</view>
		</view>
	</view>
</template>
<style lang="scss" scoped>
	.layout {

		.head {
			text-align: center;
			padding: 10rpx 0;
			font-size: 26rpx;
		}

		.search {
			margin: 30rpx;
			border: 1px solid #eee;
			padding: 0 20rpx;
			height: 70rpx;
		}

		.box {
			padding: 10rpx 30rpx;
			border-bottom: 1px solid #eee;
			;
		}
	}
</style>